package com.lenovo.lcdm.dcm.handler;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lenovo.lcdm.dcm.entity.DummyConfigurableModel;
import com.lenovo.lcdm.dcm.entity.DummyConfigurableModelMaster;
import com.lenovo.lcdm.dcm.entity.PortfolioOffering;
import com.lenovo.lcdm.dcm.service.DummyConfigurableModelMasterService;
import com.lenovo.lcdm.dcm.service.DummyConfigurableModelService;
import com.lenovo.lcdm.dcm.service.PortfolioOfferingService;
import com.lenovo.lcdm.dcm.vo.DcmHistoryVo;
import com.lenovo.lcdm.dcm.vo.DummyConfigurableModelVo;
import com.lenovo.lcdm.integration.config.ConsumerMessageHandler;
import com.lenovo.lcdm.integration.utils.KafkaHelper;
import org.checkerframework.checker.nullness.qual.Nullable;

import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PortfolioConsumerHandler implements ConsumerMessageHandler {

    @Override
    public void handleMessage(String msg) {
        PortfolioOfferingService portfolioOfferingService = SpringUtil.getBean(PortfolioOfferingService.class);
        DummyConfigurableModelMasterService dummyConfigurableModelMasterService = SpringUtil.getBean(DummyConfigurableModelMasterService.class);
        DummyConfigurableModelService dummyConfigurableModelService = SpringUtil.getBean(DummyConfigurableModelService.class);
        PortfolioOffering portfolioOffering = JSONUtil.toBean(msg, PortfolioOffering.class);
        JSONObject jsonObject = JSONUtil.parseObj(msg);
        portfolioOffering.setOfferingName(jsonObject.get("productName") == null ? "" : String.valueOf(jsonObject.get("productName")));
        portfolioOffering.setJsonData(jsonObject);
        portfolioOffering.setFormFactor(jsonObject.get("formFactor2") == null ? "" : String.valueOf(jsonObject.get("formFactor2")));
        portfolioOffering.setBusinessUnit(jsonObject.get("businessUnit") == null ? "" : String.valueOf(jsonObject.get("businessUnit")));
        portfolioOffering.setProjectPlanningCycle(jsonObject.get("planningCycle") == null ? "" : String.valueOf(jsonObject.get("planningCycle")));
        List<PortfolioOffering> list = portfolioOfferingService.lambdaQuery().eq(PortfolioOffering::getProductMasterId, portfolioOffering.getProductMasterId()).list();
        if (CollectionUtil.isNotEmpty(list)) {
            if (!list.get(0).getOfferingName().equals(portfolioOffering.getOfferingName())) {
                dummyConfigurableModelMasterService.list(Wrappers.lambdaQuery(DummyConfigurableModelMaster.class).eq(DummyConfigurableModelMaster::getName, list.get(0).getOfferingName())).forEach(dummyConfigurableModelMaster -> {
                    dummyConfigurableModelMaster.setName(portfolioOffering.getOfferingName());
                    dummyConfigurableModelMasterService.updateById(dummyConfigurableModelMaster);
                    List<DcmHistoryVo> dcmHistoryVos = dummyConfigurableModelService.getDcmHistoryByMasterId(dummyConfigurableModelMaster.getId());
                    DcmHistoryVo dcmHistoryVo = dcmHistoryVos.get(0);
                    DummyConfigurableModel dummyConfigurableModel = dummyConfigurableModelService.getById(dcmHistoryVo.getId());
                    publishDataToLPC(dummyConfigurableModelMaster.getNumber(), portfolioOffering.getOfferingName(), dummyConfigurableModel.getGeo());
                });
            }
            portfolioOffering.setId(list.get(0).getId());
            portfolioOfferingService.updateById(portfolioOffering);
        } else {
            portfolioOfferingService.save(portfolioOffering);
        }
    }

    private void publishDataToLPC(String number, String offeringName, String geo) {
        HashMap<String, Object> data = Maps.newHashMap();
        String timestamp = LocalDateTimeUtil.format(LocalDateTimeUtil.now(), DatePattern.NORM_DATETIME_PATTERN);
        data.put("trigger", "Auto");
        data.put("sendTimestamp", timestamp);
        data.put("updateTimestamp", timestamp);
        data.put("dataType", "dcm name");
        data.put("triggerNumber", "DCM" + System.currentTimeMillis());
        ArrayList<Map<String, String>> objects = Lists.newArrayList();
        objects.add(Map.of("number", number, "name", offeringName, "GEO", geo));
        data.put("data", objects);
        KafkaHelper.publish("model-name", JSONUtil.toJsonStr(data));
    }

}
